// 新建coze.js 文件

// 使用流式数据响应推荐使用Coze SDK 调用
import { CozeAPI } from "@coze/api";
// 这里可以使用store获取token动态配置
import http from "axios";

// 创建单例 API 客户端
const token = "pat_dVDW2eGKk09bNxv261NyGYKM6FNopk638bLy6yudPT2FSRxUEF0wGFml71fZPUWM";

const apiClient = new CozeAPI({
  token: token,
  baseURL: "https://api.coze.cn",
  allowPersonalAccessTokenInBrowser: true,
});

console.log(apiClient, "apiClient");

// 发送消息到 Coze
const getMessage = async (message: string) => {
    const stream = await apiClient.chat.stream({ // 返回值是一个异步生成器（AsyncGenerator）
        bot_id: "7508933344663765002",
        user_id: "test_user",
        additional_messages: [
            {
                role: "user" as any,
                content: message,
            },
        ],
        auto_save_history: true,
        stream: true,
    });
    
    let answer = "";
    let done = false;
    
    while (!done) {
        const result = await stream.next();
        done = result.done;
        
        if (!done && result.value) {
            const data = result.value;
            if (data.data && data.data.role === "assistant" && data.data.type === "answer" && !data.data.created_at) {
                answer += data.data.content;
            }
        }
    }
    
    return answer;
};

// 上传文件
const uploadFile = (file: File) => {
  const formData = new FormData();
  formData.append('file', file);
  
  return http.post("https://api.coze.cn/v1/files/upload", formData, {
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "multipart/form-data",
    },
  });
};

// 导出 API 方法
const cozeApi = {
  getMessage,
  uploadFile,
};

export default cozeApi;